<template>
  <view class="signBox">
    <canvas canvas-id="canvasid" class="mycanvas"  disable-scroll="true" @touchstart="ontouchstart" @touchmove="touchmove" @touchend="touchend"/>
		<u-button color='#fe5e10' plain text="清除" size="small" @click="clear" :customStyle="{margin: '30rpx 0 0 auto', width: 'fit-content'}" />
  </view>
</template>

<script>
let oc;
import { baseUrl } from "@/utils/baseUrl.js"
export default {	
  data() {
    return {
      oc:"",
      points:[],
      screenWidth: '',
			screenHeight: '',
      disabled: false
    }
  },
  mounted(){
    this.initCanvas()
		uni.getSystemInfo({
			success: e => {
				this.screenWidth = e.screenWidth * 0.765333;
				this.screenHeight = e.screenHeight * 0.34763;
			}
		})
  },
  methods: {
    // 画布初始
    initCanvas() {
      oc = uni.createCanvasContext('canvasid', this);
      //设置画笔样式
      oc.lineWidth = 4;
      oc.lineCap = "round";
      oc.lineJoin = "round";
      oc.fillStyle = "#fff";
    },
    //触摸开始，获取到起点
    ontouchstart(e) {
      const startX = e.changedTouches[0].x;
      const startY = e.changedTouches[0].y;
      let startPoint = {X:startX,Y:startY};
      this.points.push(startPoint);
      oc.beginPath();
    },
    //触摸移动，获取到路径点
    touchmove(e){
      let moveX = e.changedTouches[0].x;
      let moveY = e.changedTouches[0].y;
      let movePoint = {X:moveX,Y:moveY};
      this.points.push(movePoint); 
      let len = this.points.length;
      if(len>=2){
        this.draw();
      }
    },
    // 触摸结束，将未绘制的点清空防止对后续路径产生干扰
    touchend(){                   
      this.points=[];
    },
    /* ***********************************************
    #   绘制笔迹
    #   1.为保证笔迹实时显示，必须在移动的同时绘制笔迹
    #   2.为保证笔迹连续，每次从路径集合中区两个点作为起点（moveTo）和终点(lineTo)
    #   3.将上一次的终点作为下一次绘制的起点（即清除第一个点）
    ************************************************ */
    draw(){
      let point1 = this.points[0]
      let point2 = this.points[1]
      this.points.shift()
      oc.moveTo(point1.X, point1.Y)
      oc.lineTo(point2.X, point2.Y)
      oc.stroke()
      oc.draw(true)
    },
    //清空画布
    clear(){
      oc.clearRect(0, 0, this.screenWidth, this.screenHeight);
      oc.draw(true);
    },
    // 完成绘画并保存到本地
    async finish() {
      this.disabled = true
      let _this = this
      let coorArr = await this.getImagePixel()
      if(!coorArr){
        _this.$u.toast('签名失败，请重试')
        this.disabled = false
        return
      }
      if(coorArr.endY==20 && coorArr.endX==20){
        _this.$u.toast('请输入签名！')
        this.disabled = false
        return
      }
      uni.canvasToTempFilePath({
        canvasId: 'canvasid',
        x: coorArr.startX,
        y: coorArr.startY,
				fileType:'jpg',
        width: coorArr.endX - coorArr.startX,
        height: coorArr.endY - coorArr.startY,
        success: function(res) {
					uni.uploadFile({
						url: baseUrl+'upload/file', 
						filePath: res.tempFilePath,
						name: 'image',
						success: (res) => {
							res = JSON.parse(res.data)
							if(res.code === 200){
								_this.$emit('uploadFinish', res.data)
							} else {
								_this.disabled = false
								_this.$u.toast('签名上传失败！')
							}
						}
					})
        }
      }, _this)
    },
    // 获取画布内容像素边界
    getImagePixel(){
      return new Promise((resolve, reject) => {
        uni.canvasGetImageData({
          canvasId: 'canvasid',
          x: 0,
          y: 0,
          width: this.screenWidth,
          height: this.screenHeight,
          success(res) {
            if(res.errMsg == 'canvasGetImageData:ok'){
              let startX = res.width,
                  startY = res.height,
                  endX = 0,
                  endY = 0;
              for (let col = 0; col < res.width; col++) {
                for (let row = 0; row < res.height; row++) {
                  const pos = (row * res.width + col) * 4;
                  if (res.data[pos] > 0 || res.data[pos + 1] > 0 || res.data[pos + 2] || res.data[pos + 3] > 0) {
                    endY = Math.max(row, endY)
                    endX = Math.max(col, endX)
                    startY = Math.min(row, startY)
                    startX = Math.min(col, startX)
                  }
                }
              }
              // 设置边距
              startX -= 10
              startY -= 10
              endX += 10
              endY += 10
              resolve({startX,startY,endX,endY})
            }else{
              resolve(false)
            }
          }
        }, this)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.signBox {
  background-color: #fafafa;
	padding: 30rpx;
	border-radius: 16rpx;
}
.mycanvas {
  width: 100%;
	height: 460rpx;
	border: 2rpx dashed #ddd;
}
</style>